# Definition for singly-linked list.

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
    
    def load_list(self, l):
        self.val = l[0]
        p = self
        for i in l[1:]:
            p.next = ListNode(i)
            p = p.next
        return self
    
    def dump_list(self):
        a = [self.val]
        p = self
        while p.next:
            p = p.next
            a.append(p.val)
        return a

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        p, q = l1, l2
        c, p.val = divmod(p.val + q.val, 10)
        while p.next and q.next:
            p, q = p.next, q.next
            s = p.val + q.val + c
            c, p.val = divmod(s, 10)
        if q.next:
            p.next = q.next
        while p.next:
            p = p.next
            c, p.val = divmod(p.val + c, 10)
        if c == 1:
            p.next = ListNode(val=1)
        return l1

if __name__ == '__main__':
    a = [9,9,9,9,9,9,9]
    b = [9,9,9,9]
    l1, l2 = ListNode(), ListNode()
    l1 = l1.load_list(a)
    l2 = l2.load_list(b)
    c = Solution()
    l3 = c.addTwoNumbers(l1,l2)
    print(l3.dump_list())